import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/token'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout/home'
  },
  {
    // 登录页
    path: '/login',
    component: () => import(/* webpackChunkName: "Login" */ '@/views/Login'),
    beforeEnter: (to, from, next) => {
      // . // 登录成功不能强制返回登录
      if (getToken()?.length > 0) {
        // next(false)// 阻止
        next('/layout/home')
      } else {
        next()
      }
    }
  },
  {
    // 布局页，首页
    path: '/layout',
    component: () => import(/* webpackChunkName: "Layout" */ '@/views/Layout'),
    children: [
      {
        path: 'home',
        component: () => import(/* webpackChunkName: "Home" */ '@/views/Home'),
        meta: { isRecord: true, top: 0 } // isRecord是否需要设置滚动位置
      },
      {
        path: 'user',
        component: () => import(/* webpackChunkName: "User" */ '@/views/User')
        // beforeEnter: (to, from, next) => {
        //   console.log(to)
        //   if (getToken()?.length > 0) {
        //     next()
        //   } else {
        //     next({
        //       path: '/login'
        //     })
        //   }
        // }
      }
    ]
  },
  {
    path: '/search',
    component: () => import(/* webpackChunkName: "Search" */ '@/views/Search')
  },
  {
    // 搜索结果页
    path: '/search_result/:kw',
    component: () => import(/* webpackChunkName: "SearchResult" */ '@/views/Search/SearchResult')
  },
  {
    // 文章详细页
    path: '/article_detail',
    component: () => import(/* webpackChunkName: "ArticleDetail" */ '@/views/ArticleDetail')
  },
  {
    // 用户编辑
    path: '/user_editor',
    component: () => import(/* webpackChunkName: "UserEdit" */ '@/views/User/UserEdit')
  },
  // 小智聊天
  {
    path: '/chat',
    component: () => import(/* webpackChunkName: "Chat" */ '@/views/Chat')
  }
]

const router = new VueRouter({
  routes
})

// 全局后置钩子
router.afterEach((to, from) => {
  if (to.meta.isRecord) {
    setTimeout(() => {
      // 则把元信息中的 top 值设为滚动条纵向滚动的位置
      window.scrollTo(0, to.meta.top)
    }, 0)
  }
})
export default router
